//
//  RootViewController.m
//  Product Hunter
//
//  Created by Han Wang on 10/12/11.
//  Copyright 2011 The Masters. All rights reserved.
//

#import "RootViewController.h"
#import "ProductsViewController.h"
#import "AddItemController.h"

#define SECTION_ONE_TITLE @"Favorite Searches"
#define SECTION_TWO_TITLE @"Popular Deal Categories"


@implementation RootViewController

@synthesize searchBar = searchBar_;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *favoriteSearchesPath = [[NSBundle mainBundle] pathForResource:@"FavoriteSearches" ofType:@"plist"];
    NSMutableArray *favoriteSearches = [[NSMutableArray alloc] initWithContentsOfFile:favoriteSearchesPath];
    NSString *dealCategoriesPath = [[NSBundle mainBundle] pathForResource:@"DealCategories" ofType:@"plist"];
    NSMutableArray *dealCategories = [[NSMutableArray alloc] initWithContentsOfFile:dealCategoriesPath];
    
    rootViewData_ = [[NSMutableDictionary alloc] initWithCapacity:2];
    rootViewDataAllKeys_ = [[NSMutableArray alloc] initWithObjects:SECTION_ONE_TITLE, SECTION_TWO_TITLE, nil];
    [rootViewData_ setObject:favoriteSearches forKey:SECTION_ONE_TITLE];
    [rootViewData_ setObject:dealCategories forKey:SECTION_TWO_TITLE];
        
    searchBar_ = [[UISearchBar alloc] init];
    searchBar_.delegate = self;
    
    // Create a toolbar to have two buttons in the right
    UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 90, 44.1)];
    
    // Create the array to hold the buttons, which then gets added to the toolbar
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
    
    // Create a standard "add" button
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonPressed:)];
    addButton.style = UIBarButtonItemStyleBordered;
    [buttons addObject:addButton];
    [addButton release];
    
    // Create a spacer
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    [buttons addObject:spacer];
    [spacer release];
    
    // Create a "scan" button
    UIBarButtonItem *scanButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(scanButtonPressed:)];
    scanButton.style = UIBarButtonItemStyleBordered;
    [buttons addObject:scanButton];
    [scanButton release];
    
    // Stick the buttons in the toolbar
    [tools setItems:buttons animated:NO];
    
    [buttons release];
    
    // Put the toolbar in the nav bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    [tools release];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

#pragma mark-
#pragma mark Actions

- (IBAction) addButtonPressed:(id)sender
{
    AddItemController *addItemController =[[AddItemController alloc] initWithNibName:@"AddItemController" bundle:nil];
    addItemController.addedFavoriteSearches = [rootViewData_ objectForKey:SECTION_ONE_TITLE];
    
    UINavigationController *addNavController = [[UINavigationController alloc] initWithRootViewController:addItemController];
    [self presentModalViewController:addNavController animated:YES];
    
    [addItemController release];
    [addNavController release];
}

- (IBAction)scanButtonPressed:(id)sender
{
    
}

#pragma mark -
#pragma mark TableView configuration

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [rootViewDataAllKeys_ count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[rootViewData_ objectForKey:[rootViewDataAllKeys_ objectAtIndex:section]] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [rootViewDataAllKeys_ objectAtIndex:section];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    id aKey = [rootViewDataAllKeys_ objectAtIndex:indexPath.section];
    cell.textLabel.text = [[rootViewData_ objectForKey:aKey] objectAtIndex:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;  
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    id aKey = [rootViewDataAllKeys_ objectAtIndex:indexPath.section];
    if (aKey == SECTION_ONE_TITLE) {
        return YES;
    }
    else 
        return NO;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Delete the row from the data source.
        id aKey = [rootViewDataAllKeys_ objectAtIndex:indexPath.section];
        [[rootViewData_ objectForKey:aKey] removeObject:[[rootViewData_ objectForKey:aKey]objectAtIndex:indexPath.row]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductsViewController *productsViewController = [[ProductsViewController alloc] initWithNibName:@"ProductsViewController" bundle:nil];
    
    id aKey = [rootViewDataAllKeys_ objectAtIndex:indexPath.section];
    id string = [[rootViewData_ objectForKey:aKey] objectAtIndex:indexPath.row];
    if (indexPath.section == 1) {
        productsViewController.searchText = [@"Discount " stringByAppendingString:string];
    }
    else
        productsViewController.searchText = string;
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:productsViewController animated:YES];
    [productsViewController release];
	
}

#pragma mark -
#pragma mark UISearchBarDelegate methods

- (void)searchBarTextDidBeginEditing:(UISearchBar *)aSearchBar
{
    // only show the status bar’s cancel button while in edit mode
    aSearchBar.showsCancelButton = YES;
    aSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar
{
    aSearchBar.showsCancelButton = NO;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar
{
    [aSearchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar
{
    [aSearchBar resignFirstResponder];
    
    ProductsViewController *productsViewController = [[ProductsViewController alloc] initWithNibName:@"ProductsViewController" bundle:nil];
    productsViewController.searchText = [aSearchBar text];
    
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:productsViewController animated:YES];
    [productsViewController release];  

    }

#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [searchBar_ release];
    [rootViewData_ release];
    [rootViewDataAllKeys_ release];
    [super dealloc];
}

@end
